package com.wjk.controller;

import com.wjk.exception.UserException;
import com.wjk.pojo.User;
import com.wjk.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author: RobertWei
 * time: 2021/8/12    11:12
 * @TODO:
 */

@RequestMapping("user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("unauthentication")
    public String unauthentication(){
        return "unauthentication";
    }

    @GetMapping("unauthorization")
    public String unauthorization(){
        return "unauthorization";
    }


    @GetMapping("login")
    public String jump(){

        return "login";
    }


    @PostMapping("deal")
    public String deal(User user, HttpSession session) throws AuthenticationException, UserException {

        //没有权限管理的登录, 验证账号密码是否正确, 直接跳转到程序首页

        //权限管理的登录, 验证密码账号是否正确, 不正确, 正常提示, 正确查询账号的权限[菜单] 动态首页展示

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(user.getuAccount(),user.getuPassword());

        //  调用认证
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            throw e;
        }

        System.out.println(subject.isAuthenticated());

        user = (User) subject.getPrincipal();


        //将user放入共享域中, 返回前端
        Map<String, Object> data = userService.login(user);

        session.setAttribute("data",data);

        return "index";
    }

    @GetMapping("logout")
    public String logout(HttpSession session){

        session.removeAttribute("data");

        return "login";

    }




}
